package com.xinsoft.controller.purchase;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinsoft.common.ApprovedParam;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.controller.service.ScmPurchaseScmSaleService;
import com.xinsoft.entity.dto.*;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.ScmPurchasePageVo;
import com.xinsoft.entity.vo.ScmPurchaseVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购订单
 */
@RestController
@Slf4j
@RequestMapping("/scm/purchase")
public class ScmPurchaseController {

    @Autowired
    private ScmPurchaseService scmPurchaseService;
    @Autowired
    private ScmPurchaseItemService scmPurchaseItemService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysSupplierService sysSupplierService;
    @Autowired
    private ScmPurchasePriceService scmPurchasePriceService;
    @Autowired
    private ScmPurchasePlanService scmPurchasePlanService;
    @Resource
    ScmPurchaseScmSaleService scmPurchaseScmSaleService;
    @Autowired
    private ApproveService approveService;


    /**
     * 暂存采购申请单
     */
    @PostMapping("/addOrUpdate")
    public Response<?> addOrUpdate(@RequestBody ScmPurchaseDto scmPurchaseDto) {
        // 参数校验
        ValidatorUtils.validateEntity(scmPurchaseDto);
        scmPurchaseDto.setPurchaseType(Const.ApproveType.CGDD);
        scmPurchaseDto.setDoClose(0);
        scmPurchaseDto.setApproveStatus(Const.ApproveStatus.STAGING);
        scmPurchaseScmSaleService.addOrUpdate(scmPurchaseDto);
        return Response.succeed();
    }

    /**
     * 提交采购申请单
     */
    @PostMapping("/submintApprove")
    public Response<?> submintApprove(@RequestBody ScmPurchaseDto scmPurchaseDto) {
        // 参数校验
        ValidatorUtils.validateEntity(scmPurchaseDto);
        scmPurchaseDto.setPurchaseType(Const.ApproveType.CGDD);
        scmPurchaseDto.setDoClose(0);
        scmPurchaseDto.setApproveStatus(Const.ApproveStatus.SUBMIT);
        return scmPurchaseScmSaleService.submintApprove(scmPurchaseDto);
    }

    /**
     * 审批采购申请单 scm/purchaseContract/closeOfConcatract
     */
    @PostMapping("/approved")
    public Response<?> approved(@Validated @RequestBody ApprovedParam param) {
        log.info("采购申请单-审批参数：{}", JSON.toJSONString(param));
        Response<?> approved = approveService.approved(param, Const.ApproveType.CGDD);
        // todo 审批成功，将销售价格写入物料销售价格明细
        ScmPurchase scmPurchase = scmPurchaseService.getById(param.getId());
        if (approved.isSuccess() && Const.ApproveStatus.APPROVED.equals(scmPurchase.getApproveStatus())) {
            SysSupplier supplierId = sysSupplierService.getById(scmPurchase.getSupplierId());
            List<ScmPurchaseItem> itemList = scmPurchaseItemService.list(Wrappers.lambdaQuery(ScmPurchaseItem.class).eq(ScmPurchaseItem::getPurchaseId, param.getId()));
            List<ScmPurchasePrice> priceList = new ArrayList<>();
            itemList.forEach(item->{
                ScmPurchasePrice price = new ScmPurchasePrice();
                price.setMaterialId(item.getMaterialId());
                price.setTaxUnitPrice(item.getTaxUnitPrice());
                price.setNeedNum(item.getNeedNum());
                price.setPurchaseTime(scmPurchase.getUpdateTime());
                price.setSupplierId(scmPurchase.getSupplierId());
                price.setSupplierName(ObjectUtil.isEmpty(supplierId) ? "" : supplierId.getSupplierName());
                priceList.add(price);
            });
            scmPurchasePriceService.saveBatch(priceList);
        }
        return approved;
    }

    /**
     * 删除采购订单
     */
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Long> ids) {
        List<ScmPurchase> purchasePlansOfStaging = scmPurchaseService.list(new LambdaQueryWrapper<ScmPurchase>()
                .in(ScmPurchase::getId, ids).eq(ScmPurchase::getApproveStatus,Const.ApproveStatus.STAGING));
        if (ids.size() != purchasePlansOfStaging.size()){
            return Response.fail("不能删除非暂存状态单据，操作失败！");
        }
        scmPurchaseService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * 终止采购订单
     */
    @GetMapping("/close")
    public Response<?> close(@ApiParam(value = "ids") @RequestParam(value = "ids", required = true) List<Integer> ids,
                             @ApiParam(value = "关闭状态（0未关闭，1关闭）") @RequestParam(value = "doClose", required = true) Integer doClose) {
        List<ScmPurchase> purchaseList = ids.stream().map(item -> {
            ScmPurchase scmPurchase = new ScmPurchase();
            scmPurchase.setId(item);
            scmPurchase.setDoClose(doClose);
            return scmPurchase;
        }).collect(Collectors.toList());
        scmPurchaseService.saveOrUpdateBatch(purchaseList);
        return Response.succeed();
    }

    /**
     * 行关闭
     */
    @GetMapping("/closeRow")
    public Response<?> closeRow(@ApiParam(value = "主表id") @RequestParam(value = "id", required = true) Integer id,
                             @ApiParam(value = "子表id") @RequestParam(value = "itemId", required = true) Integer itemId,
                                @ApiParam(value = "关闭状态（0未关闭，1关闭）") @RequestParam(value = "doClose", required = true) Integer doClose) {
        ScmPurchase purchaseDO = scmPurchaseService.getById(id);
        if (purchaseDO.getApproveStatus().equals(Const.ApproveStatus.STAGING)){
            return Response.fail("暂存状态单据不能行关闭");
        }
        ScmPurchaseItem scmPurchaseItem = new ScmPurchaseItem();
        scmPurchaseItem.setId(id);
        scmPurchaseItem.setDoClose(doClose);
        scmPurchaseItemService.updateById(scmPurchaseItem);
        return Response.succeed();
    }

    /**
     * 分页
     */
    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody ScmPurchasePageParam scmPurchasePageParam) {
        scmPurchasePageParam.setUserId(TokenUtil.getUserId());
        if (ObjectUtil.isNotEmpty(scmPurchasePageParam.getType()) && scmPurchasePageParam.getType().equals(4)){
            List<Integer> usersOfDept = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, TokenUtil.getDeptId()))
                    .stream().map(SysUser::getId).collect(Collectors.toList());
            scmPurchasePageParam.setUsersOfDept(usersOfDept);
        }
        return scmPurchaseService.findPageListByParam(scmPurchasePageParam);
    }
    /**
     * 获取采购订单详情
     */
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", required = true) Integer id) {
        ScmPurchaseVo scmPurchase = scmPurchaseScmSaleService.getScmPurchase(id);
        scmPurchase.setScmApproveHisList(approveService.approvalHistory(id, Const.ApproveType.CGDD));
        return Response.succeed(scmPurchase);
    }

    /**
     * 历史售价
     * @return {@link Response}<{@link ?}>
     */
    @GetMapping("/historyPrice")
    public Response<?> historyPrice(@RequestParam("clientId") Integer clientId , @RequestParam("materialId") Integer materialId){
        return Response.succeed(scmPurchaseService.historyPrice(clientId,materialId));
    }

    /**
     * 采购申请单分页列表(导出)
     */
    @PostMapping("/export")
    public Response<?> export(@Valid @RequestBody ScmPurchasePageParam scmPurchasePageParam, HttpServletResponse response) throws Exception {
        scmPurchasePageParam.setUserId(TokenUtil.getUserId());
        List<ScmPurchasePageVo> planVos = scmPurchaseService.findListByParam(scmPurchasePageParam);
        ExcelUtils.exportByEasypoi(planVos, ScmPurchasePageVo.class, "采购订单", "采购订单", response, "采购订单");
        return Response.succeed();
    }
}
